<?php

/**
 * listing actions.
 *
 * @package    master_directory
 * @subpackage listing
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class listingActions extends sfActions
{
   public function executeIndex(sfWebRequest $request)
  {
  	$this->form = new TemplateForm();
  	
  	$this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  	
    $this->selected_directory = $this->getUser()->getAttribute("selected_directory") == null ? $this->master_directories[0]->getId() : $this->getUser()->getAttribute("selected_directory");
    
    //$this->templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplates();
    $this->lists = Doctrine_Core::getTable('Listing')->retreiveListsByDirectory($this->selected_directory);
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->selected_directory);

    $this->categories = $this->getCategoriesWithLevels($all_categories);
    
    
    $this->levelIds =  array();

  }
  
  public function executeLoadDirectoryData(sfWebRequest $request){
  	
  	$directory_id = $request->getParameter('directory_id');
  	
  	$form = new TemplateForm();
  	
  	$master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  	
    //$templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplates();
    $lists = Doctrine_Core::getTable('Listing')->retreiveListsByDirectory($directory_id);
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);

    $categories = $this->getCategoriesWithLevels($all_categories);
    
    $selected_directory = $directory_id;
    
    $this->getUser()->setAttribute('selected_directory',$directory_id);
    
    return $this->renderPartial('template_super_container',array('form'=>$form, 'master_directories' => $master_directories, 'selected_directory' => $directory_id, 'categories'=> $categories, 'levelIds' => array(), 'lists' => $lists));
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->listing = Doctrine_Core::getTable('Listing')->find(array($request->getParameter('id')));
    
    $this->forward404Unless($this->listing);

    $listingToLevel = Doctrine_Core::getTable('Listing2level')->getListingLevelsByListingId($this->listing->getId());
    
    $directory_id = $this->listing->getDirectoryId();
    
  	$form = new ListingForm($this->listing);
  	
  	$master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  	
   $lists = Doctrine_Core::getTable('Listing')->retreiveListsByDirectory($directory_id);
    
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);

    $categories = $this->getCategoriesWithLevels($all_categories);
    
    
    //$categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
    $selected_directory = $directory_id;
    
    $levelIds =  array();   
    
  foreach ($listingToLevel as $l2l){
    	array_push($levelIds, $l2l->getLevelId());
    }
    

    return $this->renderPartial ('template_super_container', array('form' => $form, 'master_directories' => $master_directories, 'selected_directory' => $selected_directory, 'categories' => $categories, 'levelIds' => $levelIds,'lists' => $lists));
    
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new TemplateForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

	$form = new ListingForm();
    
    $this->processForm($request, $form);
    
    $directory_id = $form->getObject()->getDirectoryId();
    
    $directory = Doctrine_Core::getTable('MasterDirectory')->find(array($directory_id));
    
   
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
    $this->categories = $this->getCategoriesWithLevels($all_categories);
    
    foreach ($this->categories as $category) {
    	
    	$root_level = Doctrine_Core::getTable('Level')->getRootLevel($category->getId());
       	$the_table = Doctrine_Core::getTable('Level');
       	$the_table->setChildren();
       	$the_table->getCategoryChildrenList($root_level);
       	foreach ($the_table->getChildren() as $level) {
       		
       		if($request->getParameter('check_'.$level->getId())){
				$listing2level = new Listing2level();
				$listing2level->setListingId($form->getObject()->getId());
				$listing2level->setLevelId($level->getId());
				$listing2level->save();
       		}
   		}
    }
    
    $this->selected_directory = $directory_id;
    

    $this->form = new ListingForm();
    
    $master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
    
    //$templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplates();
    
    $lists = Doctrine_Core::getTable('Listing')->retreiveListsByDirectory($directory_id);
    
    $this->getUser()->setFlash('saved_flash', 'Object saved',false);
    
    return $this->renderPartial('template_super_container',array('form'=>$this->form, 'master_directories' => $master_directories, 'selected_directory' => $directory_id, 'categories'=> $this->categories, 'levelIds' => array(), 'lists' => $lists));
  }
  
  

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($template = Doctrine_Core::getTable('Template')->find(array($request->getParameter('id'))), sprintf('Object template does not exist (%s).', $request->getParameter('id')));
    $this->form = new TemplateForm($template);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($listing = Doctrine_Core::getTable('Listing')->find(array($request->getParameter('id'))), sprintf('Object template does not exist (%s).', $request->getParameter('id')));
    $form = new ListingForm($listing);

    $directory_id = $form->getObject()->getDirectoryId();
    $this->processForm($request, $form);

    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    $this->categories = $this->getCategoriesWithLevels($all_categories);
     
    Doctrine_Core::getTable('Listing2level')->deleteListing2Levels($form->getObject()->getId());
    
    foreach ($this->categories as $category) {
    	
    	$root_level = Doctrine_Core::getTable('Level')->getRootLevel($category->getId());
       	$the_table = Doctrine_Core::getTable('Level');
       	$the_table->setChildren();
       	$the_table->getCategoryChildrenList($root_level);
       	foreach ($the_table->getChildren() as $level) {
       		
       		if($request->getParameter('check_'.$level->getId())){
				$listing2level = new Listing2level();
				$listing2level->setListingId($form->getObject()->getId());
				$listing2level->setLevelId($level->getId());
				$listing2level->save();
       		}
       	     		
   		}
    }    
    
    
    $this->selected_directory = $directory_id;

    $this->form = new ListingForm();
    
    $master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
    
    $lists = Doctrine_Core::getTable('Listing')->retreiveListsByDirectory($directory_id);
    
    $this->getUser()->setFlash('saved_flash', 'Object saved',false);
   
    
    return $this->renderPartial('template_super_container',array('form'=>$this->form, 'master_directories' => $master_directories, 'selected_directory' => $directory_id, 'categories'=> $this->categories, 'levelIds' => array(), 'lists' => $lists));    
    
  }

  public function executeDelete(sfWebRequest $request)
  {
    //$request->checkCSRFProtection();

    $this->forward404Unless($listing = Doctrine_Core::getTable('Listing')->find(array($request->getParameter('id'))), sprintf('Object template does not exist (%s).', $request->getParameter('id')));
    
    Doctrine_Core::getTable('Listing2level')->deleteListing2Levels($listing->getId());
    $listing->delete();
    
    $form = new ListingForm();
  	
  	$master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
  	
    $lists = Doctrine_Core::getTable('Listing')->retreiveListsByDirectory($master_directories[0]->getId());
    
    //$categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($master_directories[0]->getId());
    
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($master_directories[0]->getId());

    $this->categories = $this->getCategoriesWithLevels($all_categories);
    
    $selected_directory = $master_directories[0]->getId();
    
    return $this->renderPartial('template_super_container',array('form'=>$form, 'master_directories' => $master_directories, 'selected_directory' => $selected_directory, 'categories'=> $this->categories, 'levelIds' => array(), 'lists' => $lists));

    //$this->redirect('templates/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
   // if ($form->isValid())
   // {
      $template = $form->save();

      //$this->redirect('templates/edit?id='.$template->getId());
    //}
  }
  
  protected function getCategoriesWithLevels($all_categories){
    $categories_with_levels = array();
    
    foreach ($all_categories as $a_category){
    	if (count($a_category->getLevel()) > 0){
    		array_push($categories_with_levels, $a_category);
    	}
    }
    return $categories_with_levels;
  }
  
  
  
  public function executeGetCsv(sfWebRequest $request){
  	$directory = $request->getParameter("listing_directory_id");
  	
  	
  	
  	/*$categories = $request->getParameter("categories");*/
  	
  	
    $all_categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory);
    $categories = $this->getCategoriesWithLevels($all_categories);
    $directory_name =  Doctrine_Core::getTable('MasterDirectory')-> find($directory);
	$downloadFile = sfConfig::get('sf_upload_dir') . '/csv/' . str_replace(" ", "-", trim($directory_name->getName()))  . "-listing-content.csv";
	
  	$handle = fopen($downloadFile,"w+") or die ("unable to open file");    
    
    foreach ($categories as $category) {
	    
    	$is_inclusive = $request->getParameter('chb_inclusive_'.$category->getId()) ? true : false;
    	$root_level = Doctrine_Core::getTable('Level')->getRootLevel($category->getId());
       	$the_table = Doctrine_Core::getTable('Level');
       	$the_table->setChildren();
       	$the_table->getCategoryChildrenList($root_level);
       	
       	
       	foreach ($the_table->getChildren() as $level) {
       		
       		if($request->getParameter('check_'.$level->getId())){
       			
       			
				$the_table = Doctrine_Core::getTable ( 'Level' );
				$the_table->setTreePath();
				$the_table->findTreePath($level);
				$outside_tree_path = $the_table->getTreePath();
				$category_content = Doctrine_Core::getTable('CategoryContent');
				$category_content->setContentArr();
				$contents = Doctrine_Core::getTable('CategoryContent')->getContentsByTreePath($outside_tree_path, $level->getCategoryId());
       			
				foreach ($contents as $content){
					$line = array();
					
					$level_data = array();
					$content_data = array();
					
	       			array_push($line, $category->getMasterDirectory());
		    		array_push($line, "Category: " . $category);

		    		array_push($level_data, "Level: " . $level->getName() . "-" . $level->getId());
		    		//array_push($level_data, "Level ID: " . $level->getId());
		    		
		    		array_push($content_data, $content->getName() . "-" . $content->getId());
		    		//array_push($content_data, $content->getName() ." ID: " . $content->getId());
		    		
					if($is_inclusive){
						$parent_level = $level;
						$parent_content = $content;
						while ($parent_level->getParentId() != null){
							$parent_level = Doctrine_Core::getTable ( 'Level' )->find($parent_level->getParentId());
							$parent_content = Doctrine_Core::getTable ( 'CategoryContent' )->find($parent_content->getParentId());
				    		
				    		//array_unshift($level_data, "Level ID: " . $level->getId());
							array_unshift($level_data, "Level: " . $parent_level->getName(). "-" . $parent_level->getId());
				    		
				    		array_unshift($content_data, $parent_content->getName() ."-" . $parent_content->getId());
				    		//array_unshift($content_data, $content->getName());
				    		
						}
					}					
					$level_content_arr = array_merge($level_data, $content_data);
					$line = array_merge($line, $level_content_arr);		

					fputcsv($handle, $line);  
					
				}
       			
       		}
       	     		
   		}
   		
    }

    fclose($handle);
  	
    $this->prepareContent($downloadFile);
    
	return sfView::NONE;  	
  	
  }
  
  //public function execute
  
  protected function prepareContent($downloadFile){
  	//header("Content-Type: application/vnd.ms-excel, charset=UTF-8");
    header("Content-Type: application/force-download");
    header("Content-Transfer-Encoding: binary");
    header("Content-Disposition: attachment;filename=".substr($downloadFile, strrpos($downloadFile, "/")+1, strlen($downloadFile)- strrpos($downloadFile, "/")+1));
    header("Content-Length: ".filesize($downloadFile));
    header('Content-Encoding: UTF-8');
	header('Content-Type: text/csv; charset=UTF-8;');
    header("Pragma: no-cache");
    header("Expires: 0");
    readfile($downloadFile);
  }
  
}
